import {deleteCartGoods, getCartList, getCheckCart, postAddToCart, postCheckAll, postDeleteCart} from "@/api/cart";

export default {
    namespaced:true,
    state:{
        cartInfoList:[]
    },
    mutations:{
        SET_CART_INFO_LIST(state,payload){
            state.cartInfoList = payload;
        }
    },
    actions:{
        async getCartListAsync({commit}){
            const response = await getCartList();
            commit("SET_CART_INFO_LIST",response.data.cartInfoList);
        },
        async postAddCartAsync({dispatch},payload){
            await postAddToCart(payload.skuId,payload.buyNum);
            dispatch("getCartListAsync");
        },
        async getCheckCartAsync({dispatch},{cartId,isChecked}={}){
            await getCheckCart(cartId,isChecked);
            dispatch("getCartListAsync");
        },
        async deleteCartGoodsAsync({dispatch},id){
            await deleteCartGoods(id);
            dispatch("getCartListAsync");
        },
        async postDeleteCartAsync({state,dispatch}){
            const idArr = state.cartInfoList.filter(item=> item.isChecked).map(item=>item._id);
            await postDeleteCart(idArr);
            dispatch("getCartListAsync");
        },
        async postCheckAllAsync({state,dispatch},isChecked){
            const idArr = state.cartInfoList.map(item=>item._id);
            await postCheckAll(isChecked,idArr);
            dispatch("getCartListAsync");
        }
    },
    getters:{
        countCart(state){
            let obj = {
                sumPrice:0,
                checkedNum:0
            }
            state.cartInfoList.forEach(function(item){
                if(item.isChecked){
                    obj.checkedNum++;
                    obj.sumPrice+= item.buyNum*item.cartPrice;
                }
            });
            return obj;
        }
    }
}